package com.yonyou.ucf.mdf.app.extend.event;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Sets;
import com.yonyou.cloud.common.AbstractCommonConfigKey;
import com.yonyou.cloud.middleware.MiddlewareRuntimeEnvironment;
import com.yonyou.ucf.mdd.ext.bill.meta.loader.ViewModelLoader;
import com.yonyou.ucf.mdd.ext.core.AppContext;
import com.yonyou.ucf.mdd.ext.dto.cache.MddCacheParamDTO;
import com.yonyou.ucf.mdd.ext.enums.util.EnumUtil;
import com.yonyou.ucf.mdd.ext.util.BillContextUtils;
import com.yonyou.ucf.mdd.ext.util.ExtSwitchUtil;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.module.isv.event.ISVEventListener;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.network.cryptor.EncryptionHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import redis.clients.jedis.ScanResult;

import java.util.List;
import java.util.Set;

@Slf4j
@Component
@RequiredArgsConstructor
public class ISVUIMetaCacheCleanEvent implements ISVEventListener<ISVDemoEventClass> {

  private static final String VM_CACHE_KEY = "viewmodel";
  private static final String VA_CACHE_KEY = "viewApplication";

  @Override
  public boolean onEvent(String type, ISVDemoEventClass event, EncryptionHolder holder) {
    //已经解密过了
    String content = event.getContent();
    if (StringUtils.isNotBlank(content)){
      log.info(">>>#onEvent#ISVUIMetaCacheCleanEvent接收到消息:{}", content);
      if (content != null && content.length() != 0) {
        MddCacheParamDTO mddCacheParamDTO = (MddCacheParamDTO) JSONObject.parseObject(content, MddCacheParamDTO.class);
        String domain = mddCacheParamDTO.getDomain();
        if (domain != null) {
          String appCode = (String) MiddlewareRuntimeEnvironment.get(AbstractCommonConfigKey.APP_CODE);
          /*if (!domain.equals(appCode)) {
            return true;
          }*/
        }
        cleanCache(mddCacheParamDTO);
      }
      return true;
    }
    return false;
  }
  public static void cleanCache(MddCacheParamDTO mddCacheParam) {
    if (mddCacheParam == null) {
      log.info(">>>#cleanCache#参数信息为空，不需要进行清理操作！");
      return;
    }
    // 清理缓存key信息
    String yhtTenantId = mddCacheParam.getTenantId();
    Set<String> billNoSet = mddCacheParam.getBillNos();
    String tenantId = yhtTenantId;
    if (!AppContext.confOnlyYht()) {
      // 非yht的租户，走yxy租户信息清理缓存
      tenantId = mddCacheParam.getYxyTenantId();
    }
    boolean cleanByTypes = mddCacheParam.getCleanByTypes();
    String types = mddCacheParam.getTypes();
    if (cleanByTypes) {
      log.error(">>>#onMessage#uimeta接受清理所有租户的缓存信息，缓存类型数据types:{}", types);
    } else {
      boolean cleanUIMetaCache = mddCacheParam.getCleanUIMetaCache();
      boolean cleanEnumCache = mddCacheParam.getCleanEnumCache();
      boolean cleanRuleCache = mddCacheParam.getCleanRuleCache();
      boolean cleanVACache = mddCacheParam.getCleanVACache();
      if (cleanUIMetaCache) {
        if (tenantId != null && CollectionUtils.isNotEmpty(billNoSet)) {
          for (String billNo : billNoSet) {
            if (billNo == null) {
              continue;
            }
            if (ExtSwitchUtil.isSupportUnionDb()) {
              String preKey = String.format("%s_*%s_%s", VM_CACHE_KEY, tenantId, billNo);
//              Set<String> keys = (Set<String>) AppContext.cache().scan("0",preKey + "*",1000);
              List<String> scanResult = AppContext.cache().keysByScan( preKey + "*");
              if (CollectionUtils.isNotEmpty(scanResult)) {
                for (String key : scanResult) {
                  AppContext.cache().del(key);
                }
              }
              String viewApplicationPreKey = String.format("%s_*%s_%s", VA_CACHE_KEY, tenantId, billNo);
//              Set<String> viewApplicationKeys = (Set<String>) AppContext.cache().scan("0",viewApplicationPreKey + "*",1000);
              List<String> scan = AppContext.cache().keysByScan( viewApplicationPreKey + "*");
              if (CollectionUtils.isNotEmpty(scan)) {
                for (String key : scan) {
                  AppContext.cache().del(key);
                }
              }
            } else {
              ViewModelLoader.clearCacheByBillno(tenantId, billNo);
            }
          }
        }
      }
      if (cleanVACache) {
        if (tenantId != null && CollectionUtils.isNotEmpty(billNoSet)) {
          for (String billNo : billNoSet) {
            if (billNo == null) {
              continue;
            }
            ViewModelLoader.clearVaCacheByBillno(tenantId, billNo);
          }
        }
      }
      if (cleanEnumCache) {
        try {
          if (tenantId != null) {
            EnumUtil.refreshTenantEnum(yhtTenantId);
            ViewModelLoader.clearCacheByTenant(yhtTenantId);
          }
        } catch (Exception e) {
          log.error("清理enum租户级缓存异常！，异常信息为:{}", e.getMessage(), e);
        }
      }
      if (cleanRuleCache) {
        if (tenantId != null) {
          BillContextUtils.clearRuleCacheByTenant(yhtTenantId);
        }
      }
    }
  }

  @Override
  public int priority() {
    return ISVEventListener.super.priority()-100;
  }

  @Override
  public Set<String> supportTypes() {
    return Sets.newHashSet(ISVDemoEventExtendType.UIMETA_CACHE_CLEAN);
  }

  @Override
  public Class<ISVDemoEventClass> getEventClass() {
    return ISVDemoEventClass.class;
  }
}
